<template>
  <div class="payment-page">
    <HeaderNav v-if="!isAdmin" />
    <AdminHeaderNav v-if="isAdmin" />

    <div class="payment-container">
      <div class="payment-header">
        <el-icon class="success-icon"><SuccessFilled /></el-icon>
        <h2>订单提交成功，请尽快付款</h2>
        <p class="order-info">订单号：{{ orderId }}</p>
      </div>

      <div class="payment-content">
        <!-- 倒计时 -->
        <div class="countdown-section" :class="{ 'timeout': isTimeout }" v-loading="loading">
          <template v-if="!loading">
            <template v-if="!isTimeout">
              <div class="countdown-label">请在</div>
              <div class="countdown-time">{{ formatTime(remainingTime) }}</div>
              <div class="countdown-label">内完成支付，超时订单将自动取消</div>
            </template>
            <template v-else>
              <el-icon class="timeout-icon"><WarningFilled /></el-icon>
              <div class="timeout-text">支付超时，请重新下单</div>
            </template>
          </template>
        </div>

        <!-- 订单金额 -->
        <div class="amount-section">
          <div class="amount-label">应付金额</div>
          <div class="amount-value">¥{{ amount }}</div>
        </div>

        <!-- 账户余额 -->
        <div class="balance-section">
          <div class="balance-item">
            <span class="balance-label">账户余额：</span>
            <span class="balance-value">¥{{ userBalance }}</span>
          </div>
          <div class="balance-tip" v-if="userBalance < amount">
            <el-icon><WarningFilled /></el-icon>
            余额不足，请先充值
          </div>
        </div>

        <!-- 支付方式 -->
        <div class="payment-method-section">
          <div class="method-title">支付方式</div>
          <div class="method-item selected">
            <el-icon><Wallet /></el-icon>
            <span>余额支付</span>
            <el-icon class="check-icon"><Check /></el-icon>
          </div>
        </div>

        <!-- 支付按钮 -->
        <div class="payment-actions">
          <el-button size="large" @click="cancelPayment">{{ isTimeout ? '返回首页' : '取消订单' }}</el-button>
          <el-button 
            type="primary" 
            size="large" 
            :loading="paying"
            :disabled="userBalance < amount || isTimeout"
            @click="confirmPayment"
          >
            确认付款
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { SuccessFilled, WarningFilled, Wallet, Check } from '@element-plus/icons-vue'
import HeaderNav from '../../components/layout/HeaderNav.vue'
import AdminHeaderNav from '../../components/layout/AdminHeaderNav.vue'
import { useUserStore } from '../../stores/user'
import { payOrder } from '../../api/cart'
import { getUserInfoService } from '../../api/user'
import { getOrderDetailService } from '../../api/order'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

const orderId = ref<string>('')
const amount = ref<number>(0)
const userBalance = ref<number>(0)
const remainingTime = ref<number>(15 * 60) // 15分钟倒计时（秒）
const paying = ref(false)
const isTimeout = ref(false) // 是否已超时
const loading = ref(true) // 加载状态
let timer: number | null = null

const isAdmin = computed(() => userStore.isAdmin)

// 格式化时间显示
const formatTime = (seconds: number): string => {
  const minutes = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${String(minutes).padStart(2, '0')}:${String(secs).padStart(2, '0')}`
}

// 获取订单详情并计算剩余时间
const fetchOrderDetail = async () => {
  try {
    const res: any = await getOrderDetailService(orderId.value)
    if (res.code === 0 && res.data) {
      const createTime = new Date(res.data.createTime).getTime()
      const now = Date.now()
      const expireTime = createTime + 15 * 60 * 1000 // 15分钟后过期
      const remaining = Math.floor((expireTime - now) / 1000)
      
      if (remaining <= 0) {
        // 订单已超时
        isTimeout.value = true
        remainingTime.value = 0
        ElMessage.warning('支付超时，请重新下单')
      } else {
        remainingTime.value = remaining
        isTimeout.value = false
      }
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取用户余额
const fetchUserBalance = async () => {
  try {
    const res: any = await getUserInfoService()
    if (res.code === 0 && res.data) {
      userBalance.value = res.data.balance || 0
    }
  } catch (error) {
    console.error('获取用户余额失败:', error)
  }
}

// 确认付款
const confirmPayment = async () => {
  // 检查是否超时
  if (isTimeout.value) {
    ElMessage.warning('支付超时，请重新下单')
    return
  }
  
  if (userBalance.value < amount.value) {
    ElMessage.error('余额不足，请先充值')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确认使用余额支付 ¥${amount.value} 吗？`,
      '确认支付',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    paying.value = true
    console.log('准备调用支付接口，订单ID:', orderId.value)
    const payResponse: any = await payOrder(orderId.value)
    console.log('支付接口返回:', payResponse)

    if (payResponse.code === 0) {
      ElMessage.success('支付成功！')
      // 停止倒计时
      if (timer) {
        clearInterval(timer)
      }
      // 跳转到已买到的宝贝页面
      router.push('/purchased-items')
    } else {
      ElMessage.error(payResponse.message || '支付失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('支付失败:', error)
      ElMessage.error('支付失败: ' + (error.message || '余额不足，请先充值'))
    }
  } finally {
    paying.value = false
  }
}

// 取消订单
const cancelPayment = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要取消订单吗？',
      '取消订单',
      {
        confirmButtonText: '确定',
        cancelButtonText: '返回',
        type: 'warning'
      }
    )
    
    ElMessage.info('订单已取消')
    router.push('/layout')
  } catch (error) {
    // 用户取消操作
  }
}

// 启动倒计时
const startCountdown = () => {
  timer = window.setInterval(() => {
    if (remainingTime.value > 0) {
      remainingTime.value--
    } else {
      // 倒计时结束
      if (timer) {
        clearInterval(timer)
      }
      isTimeout.value = true
      ElMessage.warning('支付超时，请重新下单')
    }
  }, 1000)
}

onMounted(async () => {
  // 从路由参数获取订单信息
  orderId.value = String(route.query.orderId || '')
  amount.value = Number(route.query.amount)

  console.log('支付页面接收到的订单ID:', orderId.value, '金额:', amount.value)
  console.log('路由参数:', route.query)

  if (!orderId.value || !amount.value) {
    ElMessage.error('订单信息错误')
    router.push('/layout')
    return
  }

  // 获取订单详情并计算剩余时间
  await fetchOrderDetail()
  
  // 如果订单未超时，获取用户余额并启动倒计时
  if (!isTimeout.value) {
    fetchUserBalance()
    startCountdown()
  }
})

onUnmounted(() => {
  // 清除定时器
  if (timer) {
    clearInterval(timer)
  }
})
</script>

<style scoped lang="scss">
.payment-page {
  min-height: 100vh;
  background: #f5f5f5;
}

.payment-container {
  max-width: 800px;
  margin: 2rem auto;
  padding: 0 1rem;
}

.payment-header {
  background: white;
  padding: 2rem;
  border-radius: 8px;
  text-align: center;
  margin-bottom: 1.5rem;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

  .success-icon {
    font-size: 4rem;
    color: #67c23a;
    margin-bottom: 1rem;
  }

  h2 {
    font-size: 1.5rem;
    color: #303133;
    margin-bottom: 0.5rem;
  }

  .order-info {
    color: #909399;
    font-size: 0.9rem;
  }
}

.payment-content {
  background: white;
  padding: 2rem;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.countdown-section {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 1.5rem;
  background: #fff7e6;
  border-radius: 8px;
  margin-bottom: 2rem;

  &.timeout {
    background: #fef0f0;
  }

  .countdown-label {
    color: #e6a23c;
    font-size: 1rem;
  }

  .countdown-time {
    font-size: 2rem;
    font-weight: bold;
    color: #e6a23c;
    margin: 0 0.5rem;
    font-family: 'Courier New', monospace;
  }

  .timeout-icon {
    font-size: 2rem;
    color: #f56c6c;
    margin-right: 0.5rem;
  }

  .timeout-text {
    font-size: 1.2rem;
    font-weight: bold;
    color: #f56c6c;
  }
}

.amount-section {
  text-align: center;
  padding: 2rem 0;
  border-bottom: 1px solid #eee;

  .amount-label {
    color: #909399;
    font-size: 0.9rem;
    margin-bottom: 0.5rem;
  }

  .amount-value {
    font-size: 2.5rem;
    font-weight: bold;
    color: #ff6b6b;
  }
}

.balance-section {
  padding: 1.5rem 0;
  border-bottom: 1px solid #eee;

  .balance-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 0.5rem;

    .balance-label {
      color: #606266;
      font-size: 1rem;
    }

    .balance-value {
      font-size: 1.2rem;
      font-weight: bold;
      color: #67c23a;
    }
  }

  .balance-tip {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    color: #e6a23c;
    font-size: 0.9rem;
    margin-top: 0.5rem;
  }
}

.payment-method-section {
  padding: 1.5rem 0;
  border-bottom: 1px solid #eee;

  .method-title {
    font-size: 1rem;
    color: #303133;
    margin-bottom: 1rem;
  }

  .method-item {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    padding: 1rem;
    border: 2px solid #dcdfe6;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s;

    &.selected {
      border-color: #409eff;
      background: #ecf5ff;

      .check-icon {
        color: #409eff;
        margin-left: auto;
      }
    }

    &:hover {
      border-color: #409eff;
    }
  }
}

.payment-actions {
  display: flex;
  gap: 1rem;
  justify-content: center;
  margin-top: 2rem;

  .el-button {
    min-width: 150px;
  }
}

@media (max-width: 768px) {
  .payment-container {
    margin: 1rem auto;
  }

  .payment-header {
    padding: 1.5rem;

    h2 {
      font-size: 1.2rem;
    }
  }

  .countdown-section {
    flex-direction: column;
    gap: 0.5rem;

    .countdown-time {
      font-size: 1.5rem;
    }
  }

  .amount-section {
    .amount-value {
      font-size: 2rem;
    }
  }
}
</style>
